<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<view class="navbar">
			<u-navbar @leftClick="onHome" leftIconSize="28" leftIcon="home" :titleStyle="titleStyle "
				leftIconColor="#fff" bgColor="rgba(255,255,255,0)" :title="store.name" @rightClick="rightClick"
				:autoBack="true">
			</u-navbar>
		</view>
		<!-- 背景 -->
		<view class="bg">
			<image :src="category[index].image.file_path" mode="widthFix" class="image"></image>
		</view>
		<!-- 选项卡 -->
		<view class="scroll-nav">
			<view class="tabs">
				<u-tabs :list="category[index].child" keyName="name" @click="onClickTabs"></u-tabs>
			</view>
			<view class="list">
				<u-scroll-list>
					<view class="item" :class="active == index?'active':''" v-for="(item,index) in avatar"
						v-on:click="onClickAvatar(index)">
						<image :src="item.image.file_path"></image>
					</view>
				</u-scroll-list>
			</view>
		</view>
		<!-- 工作区 -->
		<view class="work">
			<view class="avatar-div" id="avatar-container">
				<image class="img" id="avatar-img" :src="avatar_url"></image>
				<view class="empty-view" v-if="!userInfo">
					<image class="empty" src="/static/images/empty.svg">
					</image>
				</view>
				<image class="avatar-default " :src="avatar[active].image.file_path">
				</image>
			</view>
			<view class="btn-group">
				<view class="btn" v-if="!userInfo.user_id">
					<button class="btn-normal" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						获取头像
					</button>
				</view>
				<view class="btn" v-else>
					<u-button shape="circle" text="切换节日" @click="is_switch = true">
					</u-button>
				</view>
				<view class="btn">
					<u-button @click="onSaveImage"
						icon="https://img.alicdn.com/imgextra/i4/2064565174/O1CN01bsG1MR1o5k1e95efr_!!2064565174.png"
						shape="circle" text="保存头像" color="linear-gradient(97.71deg, #ffa462, #ff4d42 88.36%)">
					</u-button>
				</view>
				<view class="btn" v-if="store.is_upload == 20" v-on:click="onUpload">
					<u-button shape="circle" text="上传头像" color="linear-gradient(97.71deg, #ffd01e, #ff8917 60%)">
					</u-button>
				</view>
				<view class="btn" v-else>
					<u-button openType="share" shape="circle" text="发给好友"
						color="linear-gradient(97.71deg, #ffd01e, #ff8917 60%)">
					</u-button>
				</view>
			</view>
		</view>
		<view class="hideCanvasView">
			<canvas class="hideCanvas" id="default_PosterCanvasId" canvas-id="default_PosterCanvasId"
				:style="{ width: (poster.width || 10) + 'px', height: (poster.height || 10) + 'px' }"></canvas>
		</view>
		<!-- 切换节日 -->
		<view class="switch">
			<u-action-sheet @close="is_switch = false" @select="onSwitch" :actions="category" :title="store.name"
				:show="is_switch">
			</u-action-sheet>
		</view>
		<!-- 底部跳转 -->
		<view class="jump" v-if="jump.length > 0">
			<view class="head">
				<view class="title">更多工具</view>
			</view>
			<view class="grid">
				<u-grid :border="false" @click="click" col="4">
					<block v-for="(item,index) in jump" :key="index">
						<u-grid-item v-on:click="onTools(item)">
							<u-icon :name="item.image.file_path" :size="48">
							</u-icon>
							<text class="grid-text">{{ item.title }}</text>
						</u-grid-item>
					</block>
				</u-grid>
			</view>
		</view>
		<!-- 占位 -->
		<view class="empty-line" v-if="spool.video.status == 20"></view>
		<!-- 底部流量主 -->
		<view class="ad" v-if="spool.video.status == 10">
			<ad :unit-id="spool.video.id" ad-type="video" ad-theme="white"></ad>
		</view>
	</view>
</template>

<script>
	import {
		insert,
		rewarded
	} from '@/utils/ad.js';
	import _app from '@/utils/qr/app.js';
	import {
		getQr
	} from '@/utils/qr/qr.js';
	import {
		detail,
		login
	} from '@/api/user.js';
	import {
		category,
		lists
	} from '@/api/avatar.js';
	import {
		config,
		jump
	} from '@/api/system.js';
	import siteinfo from "@/siteinfo.js"
	export default {
		data() {
			return {
				titleStyle: {
					color: '#fff'
				},
				avatar_url: '',
				is_switch: false,
				store: [],
				share: [],
				poster: {},
				posterImage: '',
				canvasId: 'default_PosterCanvasId',
				userInfo: {},
				avatar: [],
				index: 0, // 一级分类下标
				current: 0, // 二级分类下标
				active: 0, //当前选中图片下标
				category: [],
				spool: [],
				jump: []
			}
		},
		onShow() {
			this.getUser()
		},
		onLoad() {
			this.getCategory()
			this.getConfig()
			this.getJump()
		},
		onShareTimeline() {
			let _this = this
			let referee_id = ''
			if (_this.userInfo.user_id) {
				referee_id = _this.userInfo.user_id
			}
			return {
				imageUrl: _this.share.cover,
				title: "@" + _this.share.title,
				path: '/pages/main/index/index?referee_id=' + referee_id
			}
		},
		onShareAppMessage() {
			let _this = this
			let referee_id = ''
			if (_this.userInfo.user_id) {
				referee_id = _this.userInfo.user_id
			}
			return {
				imageUrl: _this.share.cover,
				title: "@" + _this.share.title,
				path: '/pages/main/index/index?referee_id=' + referee_id
			}
		},
		methods: {
			onHome() {
				uni.reLaunch({
					url: '/pages/main/index/index'
				})
			},
			onChooseAvatar(e) {
				this.userInfo.avatarUrl = e.detail.avatarUrl
				this.doLogin()
			},
			onUpload() {
				let _this = this
				if (!_this.userInfo.user_id) {
					uni.showToast({
						title: '请先获取头像',
						icon: 'none'
					});
					return false;
				}
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.showLoading({
							title: '图片上传中...'
						})
						_this.doUploadFile(tempFilePaths[0])
					},
					fail(fail) {
						console.log(fail)
					}
				});
			},
			doUploadFile(filePath) {
				let _this = this
				uni.uploadFile({
					url: siteinfo.siteroot + "upload/image&wxapp_id=" + siteinfo.uniacid +
						"&token=" +
						uni.getStorageSync("token"),
					filePath: filePath,
					name: 'iFile',
					formData: {},
					success: (uploadFileRes) => {
						uni.hideLoading()
						let data = JSON.parse(uploadFileRes.data)
						_this.avatar_url = data.data.file_path
					},
					fail() {
						uni.hideLoading()
					}
				});
			},
			onTools(item) {
				if (item.type == 10) {
					uni.navigateTo({
						url: item.url
					});
					return false;
				}
				if (item.type == 20) {
					uni.navigateTo({
						url: '/pages/main/webview/index?url=' + item.url
					});
					return false;
				}
				if (item.type == 30) {
					uni.navigateToMiniProgram({
						appId: item.app_id,
						path: item.url,
						success(res) {
							// 打开成功
						}
					});
					return false;
				}
				if (item.type == 40) {
					uni.showToast({
						title: '暂不支持的类型'
					})
					return false;
				}
			},
			getJump() {
				jump({
					local: 40
				}).then(res => {
					this.jump = res.data.jump
				}).catch(err => {

				})
			},
			onSwitch(e) {
				let category = this.category
				let index = this.index
				for (let i in category) {
					if (e.category_id == category[i].category_id) {
						index = i
						break;
					}
				}
				this.index = index
				this.is_switch = false
				this.getAvatar()
			},
			getStore() {
				config({
					key: 'store'
				}).then(res => {
					this.store = res.data.config
					this.getSpool()
					uni.setNavigationBarTitle({
						title: this.store.name
					})
				}).catch(err => {

				})
			},
			getSpool() {
				let _this = this;
				config({
					key: 'spool'
				}).then(res => {
					_this.spool = res.data.config
					if (_this.spool.insert.status == 10) {
						insert.load(_this.spool.insert.id)
						insert.show()
					}
					if (_this.spool.reward.status == 10) {
						rewarded.load(_this.spool.reward.id, () => {
							_this.savefile()
						})
					}
				}).catch(err => {

				})
			},
			getConfig() {
				config({
					key: 'share'
				}).then(res => {
					this.share = res.data.config
					this.getSpool()
					this.getStore()
				}).catch(err => {

				})
			},
			onClickAvatar(index) {
				this.active = index
			},
			onClickTabs(e) {
				this.current = e.index
				this.active = 0
				this.getAvatar()
			},
			getAvatar() {
				lists({
					category_id: this.category[this.index]['child'][this.current].category_id
				}).then(res => {
					this.avatar = res.data.avatar
				}).catch(err => {

				})
			},
			getCategory() {
				category({}).then(res => {
					this.category = res.data.category
					this.getAvatar()
				}).catch(err => {

				})
			},
			getUser() {
				detail({}).then(res => {
					if (!res.data.userInfo) {
						return false;
					}
					this.userInfo = res.data.userInfo
					// let avatarUrl = this.userInfo.avatarUrl
					// this.userInfo.avatarUrl = avatarUrl.substring(0, avatarUrl.lastIndexOf('/') + 1) +
					// 	'0';
					if (this.userInfo.avatar_id) {
						this.avatar_url = this.userInfo.avatar.file_path
					} else {
						this.avatar_url = this.userInfo.avatarUrl
					}
				}).catch(err => {

				})
			},
			doLogin() {
				let _this = this
				wx.login({
					success: res => {
						login({
							referee_id: uni.getStorageSync("referee_id"),
							code: res.code,
							user_info: JSON.stringify(this.userInfo)
						}).then((ls) => {
							uni.setStorageSync('token', ls.data.token)
							uni.setStorageSync('user_id', ls.data.user_id)
							_this.doUploadFile(this.userInfo.avatarUrl)
							_this.$refs.uToast.show({
								type: 'success',
								message: '登录成功',
								complete() {}
							})
							_this.getUser()
						}).catch(err => {
							console.log(err)
						})
					}
				})
			},
			onShowModal() {
				let _this = this
				uni.showModal({
					title: '温馨提示',
					content: this.store.down_text,
					success: function(res) {
						if (res.confirm) {
							rewarded.show()
						} else if (res.cancel) {

						}
					}
				});
			},
			async onSaveImage() {
				let _this = this
				if (!_this.userInfo.user_id) {
					uni.navigateTo({
						url: '/pages/main/passport/login'
					})
					return false;
				}
				try {
					uni.showLoading({
						title: '下载中...',
						mask: true
					});
					_app.log('准备生成:' + new Date());
					const d = await getQr({
						_this: this, //若在组件中使用 必传
						type: 'testShareType',
						formData: {
							//访问接口获取背景图携带自定义数据
						},
						backgroundImage: this.avatar_url,
						posterCanvasId: this.canvasId, //canvasId
						delayTimeScale: 20, //延时系数
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([{
									type: 'image',
									url: this.avatar[this.active].image.file_path,
									dx: 0,
									dy: 0,
									infoCallBack(imageInfo) {
										return {
											dWidth: bgObj.width, // 因为设置了圆形图片 所以要乘以2
											dHeight: bgObj.height
										};
									}
								}]);
							});
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => {
							// 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					_app.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath);
					uni.hideLoading();
					this.posterImage = d.poster.tempFilePath;
					uni.setStorageSync('avatar_poster_url', this.posterImage)
					// 判断系统是否开启强制下载且当前头像是否免费
					if (_this.store.is_force == 20 && _this.spool.reward.status == 10 && _this.avatar[_this.active]
						.is_reward == 10) {
						console.log('已开启强制·直接下载')
						_this.onShowModal()
					} else {
						console.log('未开启强制·直接下载')
						_this.savefile()
					}
				} catch (e) {
					uni.hideLoading();
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
				}
			},
			/**
			 * 保存图片
			 */
			savefile() {
				//获取相册授权
				let _self = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									//这里是用户同意授权后的回调
									_self.saveImgToLocal();
								},
								fail(e) {
									uni.hideLoading();
									wx.showModal({
										content: '检测到您没打开下载图片功能权限，是否去设置打开？',
										confirmText: '确认',
										cancelText: '取消',
										success: function(res) {
											//点击“确认”时打开设置页面
											if (res.confirm) {
												wx.openSetting();
											}
										}
									});
								}
							});
						} else {
							//用户已经授权过了
							_self.saveImgToLocal();
						}
					}
				});
			},
			/**
			 * @param {Object} e
			 * 保存到相册
			 */
			saveImgToLocal(e) {
				let _self = this;
				uni.saveImageToPhotosAlbum({
					filePath: _self.posterImage,
					success: function() {
						_self.$refs.uToast.show({
							type: 'success',
							message: '头像已保存',
							complete() {}
						})
					},
					fail: function() {
						uni.hideLoading();
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.btn-normal {
		border-radius: 120rpx;
		font-size: 28rpx;
		padding: 15rpx 0rpx;
	}

	.jump {
		width: 86%;
		background-color: #fff;
		margin: 0 auto;
		padding: 15rpx;
		border-radius: 15rpx;
		margin-bottom: 30rpx;

		.head {
			margin: 15rpx;

			.title {
				font-size: 28rpx;
			}

			border-bottom: 1rpx solid #f4f4f4;
			padding-bottom: 15rpx;
		}

		.grid {
			.grid-text {
				font-size: 28rpx;
				margin: 10rpx 0rpx;
			}
		}
	}

	.empty-line {
		height: 30rpx;
	}

	.container {
		background-size: 100% 100%;
		padding-top: 420rpx;

		.hideCanvasView {
			position: relative;
		}

		.hideCanvas {
			position: fixed;
			top: -99999upx;
			left: -99999upx;
			z-index: -99999;
		}

		.work {
			width: 90%;
			margin: 30rpx auto;
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-top: 60rpx;


			.avatar-div {
				height: 360rpx;
				margin-right: 40rpx;
				position: relative;
				width: 360rpx;
				border-radius: 24rpx;
				overflow: hidden;
			}

			.avatar-div,
			.empty-view {
				-webkit-box-orient: vertical;
				-webkit-box-direction: normal;
				-webkit-box-pack: center;
				-webkit-box-align: center;
				align-items: center;
				display: flex;
				flex-direction: column;
				justify-content: center;
				z-index: 1;
			}

			.empty {
				height: 100px;
				margin-bottom: 24px;
				width: 100px;
			}

			.img {
				background-color: #fff;
				height: 100%;
				position: absolute;
				width: 100%;
				z-index: 0;
			}

			.avatar-default {
				height: 100%;
				left: 0;
				position: absolute;
				top: 0;
				width: 100%;
				z-index: 10;
			}

			.btn-group {
				width: 40%;
				display: flex;
				flex-direction: column;

				.btn {
					margin: 10rpx 0rpx;

					.u-button {
						height: 100rpx;
					}
				}
			}
		}

		.image {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			min-height: 100vh;
			width: 750rpx;
			z-index: -1;
		}

		.scroll-nav {
			width: 82%;
			margin: 0 auto;
			background-color: #fff;
			padding: 0rpx 30rpx;
			z-index: 999;
			border-radius: 15rpx;
			overflow: hidden;

			.tabs {
				background-color: #fff;
			}

			.list {
				margin-top: 30rpx;

				.item {
					width: 140rpx;
					height: 140rpx;
					margin-right: 20rpx;
					border: 5rpx solid #f4f4f4;

					image {
						width: 140rpx;
						height: 140rpx;
					}
				}

				.active {
					border: 5rpx solid #ff4d42;
					box-shadow: 10rpx 10rpx 10rpx #ff4d42;
				}
			}
		}
	}
</style>
